package com.example.demo.config;


import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.example.demo.util.mybatisplus.CustomizedSqlInjector;
import com.example.demo.util.mybatisplus.DefaultDBFieldHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * MybatisConfig
 *
 * @author hao.chen
 * @date 2023/5/30 10:15
 */
@Configuration
@MapperScan(basePackages = MybatisConfig.PACKAGE, sqlSessionFactoryRef = MybatisConfig.SQL_SESSION_FACTORY_NAME)
public class MybatisConfig {

    public static final String PACKAGE = "com.example.demo.dao";
    public static final String MAPPER_LOCATION = "classpath*:mapper/*.xml";
    public static final String SQL_SESSION_FACTORY_NAME = "sqlSessionFactory";

    @Primary
    @Bean(name = MybatisConfig.SQL_SESSION_FACTORY_NAME)
    public SqlSessionFactory sqlSessionFactory(@Qualifier(DataSourceConfig.DATA_SOURCE_NAME) DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setConfiguration(MybatisConfig.configuration());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MybatisConfig.MAPPER_LOCATION));

        GlobalConfig globalConfig = GlobalConfigUtils.defaults();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        globalConfig.setDbConfig(dbConfig);
        globalConfig.setSqlInjector(new CustomizedSqlInjector());
        globalConfig.setMetaObjectHandler(new DefaultDBFieldHandler());
        sessionFactory.setGlobalConfig(globalConfig);
        return sessionFactory.getObject();
    }

    public static MybatisConfiguration configuration() {
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 设置驼峰
        configuration.setMapUnderscoreToCamelCase(true);
        // 设置超时
        configuration.setDefaultStatementTimeout(20);
        // 延迟加载
        configuration.setLazyLoadingEnabled(true);
        // 积极加载
        configuration.setAggressiveLazyLoading(false);
        return configuration;
    }

}
